package com.itheima.excel;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.CellReference;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

public class ExcelParseUtils {
    public static List<String[]> processSheet(String fileName) throws IOException {
        Workbook workbook = getWorkBook(fileName);
        //创建返回对象，把每行中的值作为一个数组，所有行作为一个集合返回
        return getSheetRowsData(workbook);
    }
    public static List<String[]> processSheet(MultipartFile file) throws IOException {
        Workbook workbook = getWorkBook(file);
        //创建返回对象，把每行中的值作为一个数组，所有行作为一个集合返回
        return getSheetRowsData(workbook);
    }

    private static Workbook getWorkBook(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        //创建Workbook工作薄对象，表示整个excel
        Workbook workbook = null;
        try {
            //获取excel文件的io流
            InputStream is = new FileInputStream(fileName);
            //根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象
            if(fileName.endsWith(DateConstant.EXCEL_SUFFIX_03)){
                //2003
                workbook = new HSSFWorkbook(is);
            }else if(fileName.endsWith(DateConstant.EXCEL_SUFFIX_07)){
                //2007
                workbook = new XSSFWorkbook(is);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return workbook;
    }
    private static Workbook getWorkBook(String fileName) {
        //创建Workbook工作薄对象，表示整个excel
        Workbook workbook = null;
        try {
            //获取excel文件的io流
            InputStream is = new FileInputStream(fileName);
            //根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象
            if(fileName.endsWith("xls")){
                //2003
                workbook = new HSSFWorkbook(is);
            }else if(fileName.endsWith("xlsx")){
                //2007
                workbook = new XSSFWorkbook(is);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return workbook;
    }

    private static List<String[]> getSheetRowsData(Workbook workbook) throws IOException {
        List<String[]> list = new ArrayList<String[]>();
        if(workbook != null){
            for(int sheetNum = 0;sheetNum < workbook.getNumberOfSheets();sheetNum++){
                //获得当前sheet工作表
                Sheet sheet = workbook.getSheetAt(sheetNum);
                if(sheet == null){
                    continue;
                }
                //获得当前sheet的开始行
                int firstRowNum  = sheet.getFirstRowNum();
                //获得当前sheet的结束行
                int lastRowNum = sheet.getLastRowNum();
                //循环除了第一行的所有行
                for(int rowNum = firstRowNum+1;rowNum <= lastRowNum;rowNum++){
                    //获得当前行
                    Row row = sheet.getRow(rowNum);
                    if(row == null){
                        continue;
                    }
                    ArrayList<String> values = new ArrayList<>();
                    for (Iterator cit = row.cellIterator(); cit.hasNext(); ) {
                        Cell cell = (Cell)cit.next();
                        String cellValue = getCellValue(workbook,cell);
                        values.add(cellValue);
                    }
                    String[] cellValues = values.toArray(new String[values.size()]);
                    list.add(cellValues);
                }
            }
            workbook.close();
        }
        return list;
    }


    private static String getCellValue(Workbook workbook,Cell cell){
        String cellValue = "";
        if (cell == null){
            return cellValue;
        }
        switch (cell.getCellType()){
            case Cell.CELL_TYPE_NUMERIC:
                cellValue = getDateValue(cell.getCellStyle().getDataFormat(), cell.getCellStyle().getDataFormatString(),
                        cell.getNumericCellValue());
                if (cellValue == null){
                    //cell.setCellType(Cell.CELL_TYPE_STRING);
                    //cellValue = String.valueOf(cell.getStringCellValue());
                    cellValue = String.valueOf(cell.getNumericCellValue());
                }
                break;
            case Cell.CELL_TYPE_STRING:
                cellValue = String.valueOf(cell.getStringCellValue());
                break;
            case Cell.CELL_TYPE_BOOLEAN:
                cellValue = String.valueOf(cell.getBooleanCellValue());
                break;
            case Cell.CELL_TYPE_FORMULA:
                /**
                 * 格式化单元格
                 */
                FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
                cellValue = getCellValue(evaluator.evaluate(cell));
                break;
            case Cell.CELL_TYPE_BLANK:
                cellValue = "";
                break;
            case Cell.CELL_TYPE_ERROR:
                cellValue = String.valueOf(cell.getErrorCellValue());
                break;
            default:
                cellValue = "未知类型";
                break;
        }
        return cellValue;
    }
    private static String getCellValue(CellValue formulaValue) {
        String cellValue = "";
        if (formulaValue == null) {
            return cellValue;
        }
        switch (formulaValue.getCellType()) {
            case Cell.CELL_TYPE_NUMERIC:
                cellValue = String.valueOf(formulaValue.getNumberValue());
                break;
            case Cell.CELL_TYPE_STRING:
                cellValue = String.valueOf(formulaValue.getStringValue());
                break;
            case Cell.CELL_TYPE_BOOLEAN:
                cellValue = String.valueOf(formulaValue.getBooleanValue());
                break;
            case Cell.CELL_TYPE_BLANK:
                cellValue = "";
                break;
            case Cell.CELL_TYPE_ERROR:
                cellValue = String.valueOf(formulaValue.getErrorValue());
                break;
            default:
                cellValue = "未知类型";
                break;
        }
        return cellValue;
    }
    private static String getDateValue(Short dataFormat, String dataFormatString, double value){
        if (!DateUtil.isValidExcelDate(value)){
            return null;
        }
        /*
        cellValue = new SimpleDateFormat(DATE_FORMAT).format(cell.getDateCellValue());
            return cellValue;
         */

        Date date = DateUtil.getJavaDate(value);
        /**
         * 年月日时分秒
         */
        if (DateConstant.EXCEL_FORMAT_INDEX_DATE_NYRSFM_STRING.contains(dataFormatString)) {
            return DateConstant.COMMON_DATE_FORMAT.format(date);
        }
        /**
         * 年月日
         */
        if (DateConstant.EXCEL_FORMAT_INDEX_DATE_SUPPLEMENT_NYR_STRING.contains(dataFormatString)) {
            return DateConstant.COMMON_DATE_FORMAT_SUPPLEMENT_NYR.format(date);
        }

        /**
         * 年月
         */
        if (DateConstant.EXCEL_FORMAT_INDEX_DATE_NY_STRING.contains(dataFormatString) || DateConstant.EXCEL_FORMAT_INDEX_DATA_EXACT_NY.equals(dataFormat)) {
            return DateConstant.COMMON_DATE_FORMAT_NY.format(date);
        }
        /**
         * 月日
         */
        if (DateConstant.EXCEL_FORMAT_INDEX_DATE_YR_STRING.contains(dataFormatString) || DateConstant.EXCEL_FORMAT_INDEX_DATA_EXACT_YR.equals(dataFormat)) {
            return DateConstant.COMMON_DATE_FORMAT_YR.format(date);

        }
        /**
         * 月
         */
        if (DateConstant.EXCEL_FORMAT_INDEX_DATE_Y_STRING.contains(dataFormatString)) {
            return DateConstant.COMMON_DATE_FORMAT_Y.format(date);
        }
        /**
         * 星期X
         */
        if (DateConstant.EXCEL_FORMAT_INDEX_DATE_XQ_STRING.contains(dataFormatString)) {
            return DateConstant.COMMON_DATE_FORMAT_XQ + dateToWeek(date);
        }
        /**
         * 周X
         */
        if (DateConstant.EXCEL_FORMAT_INDEX_DATE_Z_STRING.contains(dataFormatString)) {
            return DateConstant.COMMON_DATE_FORMAT_Z + dateToWeek(date);
        }
        /**
         * 时间格式
         */
        if (DateConstant.EXCEL_FORMAT_INDEX_TIME_STRING.contains(dataFormatString) || DateConstant.EXCEL_FORMAT_INDEX_TIME_EXACT.contains(dataFormat)) {
            return DateConstant.COMMON_TIME_FORMAT.format(DateUtil.getJavaDate(value));
        }
        /**
         * 单元格为其他未覆盖到的类型
         */
        if (DateUtil.isADateFormat(dataFormat, dataFormatString)) {
            return DateConstant.COMMON_TIME_FORMAT.format(value);
        }

        return null;
    }
    private static String dateToWeek(Date date) {
        if (date == null){
            return "";
        }
        // 获得一个日历
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        // 指示一个星期中的某天。
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;
        return DateConstant.WEEK_DAYS[w];
    }
}
